package cn.xiaopengstack.domain.strategy.service.rule.chain.impl;

import cn.xiaopengstack.domain.strategy.model.entity.RuleChainMatterEntity;
import cn.xiaopengstack.domain.strategy.model.entity.StrategyRuleEntity;
import cn.xiaopengstack.domain.strategy.repository.IStrategyRepository;
import cn.xiaopengstack.domain.strategy.service.rule.chain.factory.DefaultLogicChainFactory;
import cn.xiaopengstack.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import cn.xiaopengstack.types.common.Constants;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author jiangyangang
 */
@Component("rule_blacklist")
@Slf4j
public class RuleBlackChainImpl extends AbstractLogicChain {
    @Resource
    private IStrategyRepository strategyRepository;

    @Override
    public DefaultLogicChainFactory.StrategyAwardVO doChain(RuleChainMatterEntity ruleChainMatterEntity) {

        StrategyRuleEntity strategyRuleEntity = strategyRepository.queryStrategyRule(ruleChainMatterEntity.getStrategy().getStrategyId(), DefaultLogicFactory.LogicModel.RULE_BLACKLIST.getCode());
        if (Objects.isNull(strategyRuleEntity)) {
            throw new AppException(ResponseCode.STRATEGY_RULE_BLACK_IS_NULL.getCode(), ResponseCode.STRATEGY_RULE_BLACK_IS_NULL.getInfo());
        }

        String ruleValue = strategyRepository.queryStrategyRuleValue(ruleChainMatterEntity.getStrategy().getStrategyId(), ruleModel().getCode());
        // 解析
        String[] ruleModelSplit = ruleValue.split(Constants.COLON);
        Integer awardId = Integer.valueOf(ruleModelSplit[0]);

        // 判断用户是否在黑名单内
        String[] blackUsers = ruleModelSplit[1].split(Constants.SPLIT);
        for (String userId : blackUsers) {
            if (userId.equals(ruleChainMatterEntity.getUser().getUserId())) {
                return DefaultLogicChainFactory.StrategyAwardVO.builder()
                        .takeOverRule(ruleModel())
                        .awardId(awardId)
                        .strategyId(ruleChainMatterEntity.getStrategy().getStrategyId()).build();
            }
        }

        return this.next().doChain(ruleChainMatterEntity);
    }


    @Override
    public DefaultLogicChainFactory.LogicModel ruleModel() {
        return DefaultLogicChainFactory.LogicModel.RULE_BLACKLIST;
    }
}
